import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    SetToken(state, token) {
      // 存入vuex
      state.token = token
      // 存入cookie
      setToken(token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.token = ''
      state.userInfo = ''
      removeToken()
      // 清空路由记录
      resetRouter()
    }
  },
  actions: {
    async logintoken({ commit }, data) {
      const res = await login(data)
      commit('SetToken', res)
    },
    async fetchUserInfo({ commit }) {
      const res = await getUserInfo()
      const res_ = await getUserDetailById(res.userId)
      commit('setUserInfo', { ...res, ...res_ })
      return res
    }
  }
}
